package cn.com.acca.ma.service.impl;

import cn.com.acca.ma.common.util.DateUtil;
import cn.com.acca.ma.common.util.PropertiesUtil;
import cn.com.acca.ma.constant.RobotPrintBuySellSuggestionFormat;
import cn.com.acca.ma.constant.WeekGoldCrossDeadCrossMethod;
import cn.com.acca.ma.model.Robot5StockTransactRecord;
import cn.com.acca.ma.pojo.ProfitAndLossRate;
import cn.com.acca.ma.pojo.StockWeekAverageClosePriceAndMa5;
import cn.com.acca.ma.pojo.StockWeekAverageHeiKinAshiClosePrice;
import cn.com.acca.ma.pojo.StockWeekAverageKD;
import cn.com.acca.ma.pojo.StockWeekDatePojo;
import cn.com.acca.ma.service.Robot5StockTransactRecordService;

import java.util.Date;
import java.util.List;

public class Robot5StockTransactRecordServiceImpl extends BaseServiceImpl<Robot5StockTransactRecordServiceImpl, Robot5StockTransactRecord> implements
        Robot5StockTransactRecordService {

    /**
     * 执行某段时间内的股票买卖交易（多种方法一起使用）
     */
    @Override
    public void doBuyAndSellByBeginDateAndEndDate_multipleMethod() {
        logger.info("执行某段时间内的股票买卖交易（多种方法一起使用）");

        String beginDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.beginDate");
        String endDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.endDate");
        Integer holdStockNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.all.holdStockNumber"));
        Integer minHoldStockNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.minHoldStockNumber"));
        Integer middleHoldStockNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.middleHoldStockNumber"));
        Boolean useBoolMethod = Boolean.parseBoolean(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.useBoolMethod"));
        Boolean useWeekMethod = Boolean.parseBoolean(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.useWeekMethod"));
        Integer closePriceUpDownBollDateNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.closePrice.up.down.boll.date.number"));
        Integer mandatoryStopLoss = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.mandatoryStopLoss"));
        Double mandatoryStopLossRate = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.mandatoryStopLossRate"));
        Integer mandatoryStopProfit = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.mandatoryStopProfit"));
        Double mandatoryStopProfitRate = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.mandatoryStopProfitRate"));
        Double top = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.top"));
        Double bottom = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.bottom"));
        Double closePriceStart = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.closePrice.start"));
        Double closePriceEnd = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.closePrice.end"));
        Integer printFormat = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.print.format"));
        Integer goldCrossDeadCrossMethod = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.multipleMethod.goldCross.deadCross.method"));

        // 获取日期列表
        List<String> dateList = stockTransactionDataDao.findDistinctDateBetweenBeginDateAndEndDate(false, beginDate, endDate);
        if (null != dateList && dateList.size() > 0) {
            for (int i = 0; i < dateList.size(); i++) {
                String currentDate = dateList.get(i);

                // 确定是做多，还是做空。判断使用哪种算法
                Boolean goldCross = false;
                Boolean deadCross = false;
                // 是否是周末
                boolean isWeekend = false;

                /*************************************** 卖股票/买股票 ***********************************************/
                // 更新robot5_account表
                robot5AccountDao.updateRobotAccountBeforeSellOrBuy(currentDate);

                // 卖股票
                robot5StockTransactRecordDao.sellOrBuy(currentDate, mandatoryStopLoss, mandatoryStopLossRate, mandatoryStopProfit, mandatoryStopProfitRate);

                // 更新robot5_account表
                robot5AccountDao.updateRobotAccountAfterSellOrBuy(currentDate);

                // 如果所有账号都已经满仓，则跳过这个交易日
                if (isFullStockInRobot5Account(holdStockNumber)) {
                    logger.info("所有账号都是满仓，因此日期【" + currentDate + "】不做任何交易，直接跳过");

                    // 更新robot5_account表的total_assets字段
                    robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                    continue;
                }

                /*************************************** 计算仓位分配 ***********************************************/
//                Integer useBoolHoldStockNumber = holdStockNumber / 2;
//                Integer useWeekHoldStockNumber = holdStockNumber / 2;
//
//                logger.info("使用Robot3Main算法的持股数量为【" + useBoolHoldStockNumber + "】，使用Robot4Main算法的持股数量为【" + useWeekHoldStockNumber + "】");
                
                Integer useBoolHoldStockNumber = null;
                Integer useWeekHoldStockNumber = null;
                ProfitAndLossRate profitAndLossRate = robot5StockTransactRecordDao.sumRobot3MainAndRobot4MainWithinLastThreeMonth(currentDate);
                if (null == profitAndLossRate 
                        || null == profitAndLossRate.getRobot3MainProfitAndLossRate()
                        || null == profitAndLossRate.getRobot4MainProfitAndLossRate()) {
                    useBoolHoldStockNumber = 20;
                    useWeekHoldStockNumber = 20;
                } else if (profitAndLossRate.getRobot3MainProfitAndLossRate().doubleValue() <= 0
                        && profitAndLossRate.getRobot4MainProfitAndLossRate().doubleValue() > 0) {
                    useBoolHoldStockNumber = 10;
                    useWeekHoldStockNumber = 30;
                } else if (profitAndLossRate.getRobot3MainProfitAndLossRate().doubleValue() > 0
                        && profitAndLossRate.getRobot4MainProfitAndLossRate().doubleValue() <= 0) {
                    useBoolHoldStockNumber = 30;
                    useWeekHoldStockNumber = 10;
                } else if (profitAndLossRate.getRobot3MainProfitAndLossRate().doubleValue() == 0
                        && profitAndLossRate.getRobot4MainProfitAndLossRate().doubleValue() == 0) {
                    useBoolHoldStockNumber = 20;
                    useWeekHoldStockNumber = 20;
                } else if (profitAndLossRate.getRobot3MainProfitAndLossRate().doubleValue() < 0
                        && profitAndLossRate.getRobot4MainProfitAndLossRate().doubleValue() < 0) {
                    if (profitAndLossRate.getRobot3MainProfitAndLossRate().doubleValue() > profitAndLossRate.getRobot4MainProfitAndLossRate().doubleValue()){
                        useBoolHoldStockNumber = 30;
                        useWeekHoldStockNumber = 10;
                    }
                    if (profitAndLossRate.getRobot3MainProfitAndLossRate().doubleValue() < profitAndLossRate.getRobot4MainProfitAndLossRate().doubleValue()){
                        useBoolHoldStockNumber = 10;
                        useWeekHoldStockNumber = 30;
                    }
                } else if (profitAndLossRate.getRobot3MainProfitAndLossRate().doubleValue() > 0
                        && profitAndLossRate.getRobot4MainProfitAndLossRate().doubleValue() > 0) {
                    double robot3MainProfitAndLossRate = profitAndLossRate.getRobot3MainProfitAndLossRate().doubleValue();
                    double robot4MainProfitAndLossRate = profitAndLossRate.getRobot4MainProfitAndLossRate().doubleValue();
                    double sum = robot3MainProfitAndLossRate + robot4MainProfitAndLossRate;
                    double robot3MainProfitAndLossRatePercentage = robot3MainProfitAndLossRate / sum;
                    double robot4MainProfitAndLossRatePercentage = robot4MainProfitAndLossRate / sum;
                    useBoolHoldStockNumber = (int) (holdStockNumber * robot3MainProfitAndLossRatePercentage);
                    useWeekHoldStockNumber = (int) (holdStockNumber * robot4MainProfitAndLossRatePercentage);
                    if (useBoolHoldStockNumber > useWeekHoldStockNumber) {
                        useWeekHoldStockNumber += 1;
                    }
                    if (useBoolHoldStockNumber < useWeekHoldStockNumber) {
                        useBoolHoldStockNumber += 1;
                    }
                } else {
                    try {
                        throw new Exception("仓位计算的程序出错了！！！");
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if (0 == useBoolHoldStockNumber) {
                    useBoolHoldStockNumber = 10;
                    useWeekHoldStockNumber = 30;
                }
                if (0 == useWeekHoldStockNumber) {
                    useBoolHoldStockNumber = 30;
                    useWeekHoldStockNumber = 10;
                }
                logger.info("Robat3Main算法的收益率总和为【" + (null != profitAndLossRate ? profitAndLossRate.getRobot3MainProfitAndLossRate() : null) + "】，"
                        + "Robat4Main算法的收益率总和为【" + (null != profitAndLossRate ? profitAndLossRate.getRobot4MainProfitAndLossRate() : null) + "】。"
                        + "使用Robot3Main算法的持股数量为【" + useBoolHoldStockNumber + "】，"
                        + "使用Robot4Main算法的持股数量为【" + useWeekHoldStockNumber + "】");

                /****************************** 使用Robot3Main的算法 **************************************/
                if (useBoolMethod) {
                    logger.info("开始使用Robot3Main的算法，过滤股票");

                    // 清空robot5_stock_filter表
                    robot5StockFilterDao.truncateTableRobotStockFilter();
                    // 根据date，从stock_transaction_data表中，向robot5_stock_filter表中插入股票代码
                    robot5StockFilterDao.insertAllStockBollByDate(currentDate);

                    // 过滤条件：只保留这个价格区间以内的股票
                    robot5StockFilterDao.filterByLessThanClosePrice(currentDate, closePriceStart, closePriceEnd);
                    // 过滤条件：如果当前交易日和前一个交易日的收盘价都大于/小于布林带上轨/下轨，并且当前交易日的收盘价小于/大于前一个交易日的收盘价，则保留
                    robot5StockFilterDao.filterByUpDownBoll(currentDate, closePriceUpDownBollDateNumber);
                    // 过滤条件：如果上一周这只股票的最高价/最低价突破/跌破周线级别布林带上轨/下轨，则保留
//                    robot5StockFilterDao.filterByLastWeekUpDownBoll(currentDate);
                    // 过滤条件：删除除过权的股票
                    robot5StockFilterDao.filterByXr(currentDate, endDate);
//                    robot5StockFilterDao.filterByXr(beginDate, endDate);

                    // 卖股票
                    robot5StockTransactRecordDao.buyOrSell(currentDate, 3, useBoolHoldStockNumber, holdStockNumber);

                    // 更新robot5_account表的total_assets字段
                    robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);
                }

                /****************************** 使用Robot4Main的算法，过滤股票 **************************************/
                if (useWeekMethod) {
                    logger.info("开始使用Robot4Main的算法，过滤股票");

                    // 如果当前日期是周末，则买股票，否则跳过这一天
                    List<StockWeekDatePojo> stockWeekDatePojoList = stockIndexWeekDao.findBeginDateAndEndDateGroupByBeginDateAndEndDateOrderByBeginDate(beginDate, endDate);
                    if (null != stockWeekDatePojoList && stockWeekDatePojoList.size() > 0) {
                        for (StockWeekDatePojo stockWeekDatePojo : stockWeekDatePojoList) {
                            Date theEndDate = stockWeekDatePojo.getEndDate();
                            if (theEndDate.equals(DateUtil.stringToDate(currentDate))) {
                                isWeekend = true;
                                logger.info("日期【" + DateUtil.dateToString(theEndDate) + "】是本周最后一个交易日，准备买入/融券");
                                break;
                            }
                        }

                        if (isWeekend) {
                            // 判断使用哪个方法决定操作方向
                            // 查找包括日期date在内的之前的两周记录的平均K和D，并按照begin_date升序排列
                            List<StockWeekAverageKD> theStockWeekAverageKDList = stockWeekDao.findThisTwoStockWeekAverageKDByDateOrderByBeginDateAsc(currentDate);
                            // 本周
                            StockWeekAverageKD thisWeekStockWeekAverageKD = theStockWeekAverageKDList.get(0);
                            // 上周
                            StockWeekAverageKD lastWeekStockWeekAverageKD = theStockWeekAverageKDList.get(1);
                            double averageKD = (thisWeekStockWeekAverageKD.getAverageK().doubleValue() + thisWeekStockWeekAverageKD.getAverageD().doubleValue()) / 2;
                            if (averageKD <= top && averageKD >= bottom) {
                                goldCrossDeadCrossMethod = WeekGoldCrossDeadCrossMethod.KD_GOLD_CROSS_DEAD_CROSS;
                                logger.info("averageKD是【" + averageKD + "】，使用KD金叉/死叉来判断操作方向");
                            } else {
                                goldCrossDeadCrossMethod = WeekGoldCrossDeadCrossMethod.HEI_KIN_ASHI_UP_DOWN;
                                logger.info("averageKD是【" + averageKD + "】，使用hei_kin_ashi上涨/下跌来判断操作方向");
                            }

                            // 判断操作方向
                            // close_price和ma5金叉死叉
                            List<StockWeekAverageClosePriceAndMa5> stockWeekAverageClosePriceAndMa5List;
                            StockWeekAverageClosePriceAndMa5 lastFirstStockWeekAverageClosePriceAndMa5;
                            StockWeekAverageClosePriceAndMa5 lastSecondStockWeekAverageClosePriceAndMa5;
                            if (goldCrossDeadCrossMethod.equals(WeekGoldCrossDeadCrossMethod.CLOSE_PRICE_MA5_GOLD_CROSS_DEAD_CROSS)) {
                                // 上周与上上周
//                          stockWeekAverageClosePriceAndMa5List = stockWeekDao.findLastTwoStockWeekAverageClosePriceAndMA5ByDateOrderByBeginDateAsc(currentDate);
                                // 本周与上周
                                stockWeekAverageClosePriceAndMa5List = stockWeekDao.findThisTwoStockWeekAverageClosePriceAndMA5ByDateOrderByBeginDateAsc(currentDate);

                                if (null != stockWeekAverageClosePriceAndMa5List && stockWeekAverageClosePriceAndMa5List.size() == 2) {
                                    lastFirstStockWeekAverageClosePriceAndMa5 = stockWeekAverageClosePriceAndMa5List.get(0);
                                    lastSecondStockWeekAverageClosePriceAndMa5 = stockWeekAverageClosePriceAndMa5List.get(1);

//                        // 如果上个星期是金叉
//                        if (lastFirstStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue() >= lastFirstStockWeekAverageClosePriceAndMa5.getAverageMA5().doubleValue()) {
//                            goldCross = true;
//                            logger.info("上个星期出现了金叉");
//                        }
//                        // 如果上个星期是死叉
//                        if (lastFirstStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue() <= lastFirstStockWeekAverageClosePriceAndMa5.getAverageMA5().doubleValue()) {
//                            deadCross = true;
//                            logger.info("上个星期出现了死叉");
//                        }

                                    // 如果上个星期比上上个星期高
//                        if (lastSecondStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue() <= lastFirstStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue()) {
//                            goldCross = true;
//                            logger.info("上个星期比上上个星期高");
//                        }
                                    // 如果上个星期比上上个星期低
//                        if (lastSecondStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue() >= lastFirstStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue()) {
//                            deadCross = true;
//                            logger.info("上个星期比上上个星期低");
//                        }

                                    // 本周平均close_price比上周平均close_price上涨了
                                    if (lastSecondStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue() <= lastFirstStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue()) {
                                        goldCross = true;
                                        logger.info("本周平均close_price比上周平均close_price上涨了");
                                    }
                                    // 本周平均close_price比上周平均close_price下跌了
                                    if (lastSecondStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue() >= lastFirstStockWeekAverageClosePriceAndMa5.getAverageClosePrice().doubleValue()) {
                                        deadCross = true;
                                        logger.info("本周平均close_price比上周平均close_price下跌了");
                                    }
                                } else {
                                    logger.warn("没有前两个星期的记录或者不足两个星期，从下一个日期开始处理");

                                    // 更新robot5_account表的total_assets字段
                                    robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                                    continue;
                                }
                            }

                            // hei_kin_ashi上涨下跌
                            List<StockWeekAverageHeiKinAshiClosePrice> stockWeekAverageHeiKinAshiClosePriceList;
                            StockWeekAverageHeiKinAshiClosePrice lastFirstStockWeekAverageHeiKinAshiClosePrice = null;
                            StockWeekAverageHeiKinAshiClosePrice lastSecondStockWeekAverageHeiKinAshiClosePrice = null;
                            if (goldCrossDeadCrossMethod.equals(WeekGoldCrossDeadCrossMethod.HEI_KIN_ASHI_UP_DOWN)) {
                                // 上周与上上周
//                          stockWeekAverageHeiKinAshiClosePriceList = stockWeekDao.findLastTwoStockWeekAverageHeiKinAshiClosePriceByDateOrderByBeginDateAsc(currentDate);
                                // 本周与上周
                                stockWeekAverageHeiKinAshiClosePriceList = stockWeekDao.findThisTwoStockWeekAverageHeiKinAshiClosePriceByDateOrderByBeginDateAsc(currentDate);

                                if (null != stockWeekAverageHeiKinAshiClosePriceList && stockWeekAverageHeiKinAshiClosePriceList.size() == 2) {
                                    lastFirstStockWeekAverageHeiKinAshiClosePrice = stockWeekAverageHeiKinAshiClosePriceList.get(0);
                                    lastSecondStockWeekAverageHeiKinAshiClosePrice = stockWeekAverageHeiKinAshiClosePriceList.get(1);

                                    // 上一周hei_kin_ashi收盘价大于上上周hei_kin_ashi收盘价
//                                if (lastSecondStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiClosePrice().doubleValue() <= lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiClosePrice().doubleValue()) {
//                                    goldCross = true;
//                                    logger.info("上一周hei_kin_ashi收盘价大于上上周hei_kin_ashi收盘价");
//                                }
                                    // 上一周hei_kin_ashi收盘价小于上上周hei_kin_ashi收盘价
//                                if (lastSecondStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiClosePrice().doubleValue() >= lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiClosePrice().doubleValue()) {
//                                    deadCross = true;
//                                    logger.info("上一周hei_kin_ashi收盘价小于上上周hei_kin_ashi收盘价");
//                                }

                                    // 如果上个星期是阳线
//                        if (lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiOpenPrice().doubleValue() <= lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiClosePrice().doubleValue()) {
//                            goldCross = true;
//                            logger.info("上个星期是阳线");
//                        }
                                    // 如果上个星期是阴线
//                        if (lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiOpenPrice().doubleValue() >= lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiClosePrice().doubleValue()) {
//                            deadCross = true;
//                            logger.info("上个星期是阴线");
//                        }

                                    // 本周hei_kin_ashi是阳线
                                    if (lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiClosePrice().doubleValue() >= lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiOpenPrice().doubleValue()) {
                                        goldCross = true;
                                        logger.info("本周hei_kin_ashi是阳线");
                                    }
                                    // 本周hei_kin_ashi是阴线
                                    if (lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiClosePrice().doubleValue() <= lastFirstStockWeekAverageHeiKinAshiClosePrice.getAverageHeiKinAshiOpenPrice().doubleValue()) {
                                        deadCross = true;
                                        logger.info("本周hei_kin_ashi是阴线");
                                    }
                                } else {
                                    logger.warn("没有前两个星期的记录或者不足两个星期，从下一个日期开始处理");

                                    // 更新robot5_account表的total_assets字段
                                    robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                                    continue;
                                }
                            }

                            // kd金叉死叉
                            List<StockWeekAverageKD> stockWeekAverageKDList;
                            StockWeekAverageKD lastFirstStockWeekAverageKD = null;
                            StockWeekAverageKD lastSecondStockWeekAverageKD = null;
                            if (goldCrossDeadCrossMethod.equals(WeekGoldCrossDeadCrossMethod.KD_GOLD_CROSS_DEAD_CROSS)) {
                                // 上周与上上周
//                          stockWeekAverageKDList = stockWeekDao.findLastTwoStockWeekAverageKDByDateOrderByBeginDateAsc(currentDate);
                                // 本周与上周
                                stockWeekAverageKDList = stockWeekDao.findThisTwoStockWeekAverageKDByDateOrderByBeginDateAsc(currentDate);

                                if (null != stockWeekAverageKDList && stockWeekAverageKDList.size() == 2) {
                                    lastFirstStockWeekAverageKD = stockWeekAverageKDList.get(0);
                                    lastSecondStockWeekAverageKD = stockWeekAverageKDList.get(1);

//                        // 如果上个星期是金叉
//                        if (lastFirstStockWeekAverageKD.getAverageK().doubleValue() >= lastFirstStockWeekAverageKD.getAverageD().doubleValue()) {
//                            goldCross = true;
//                            logger.info("上个星期出现了金叉");
//                        }
//                        // 如果上个星期是死叉
//                        if (lastFirstStockWeekAverageKD.getAverageK().doubleValue() <= lastFirstStockWeekAverageKD.getAverageD().doubleValue()) {
//                            deadCross = true;
//                            logger.info("上个星期出现了死叉");
//                        }

                                    // 如果上个星期比上上个星期高
//                        if (lastSecondStockWeekAverageKD.getAverageK().doubleValue() <= lastFirstStockWeekAverageKD.getAverageK().doubleValue()) {
//                            goldCross = true;
//                            logger.info("上个星期出现了金叉");
//                        }
                                    // 如果上个星期比上上个星期低
//                        if (lastSecondStockWeekAverageKD.getAverageK().doubleValue() >= lastFirstStockWeekAverageKD.getAverageK().doubleValue()) {
//                            deadCross = true;
//                            logger.info("上个星期出现了死叉");
//                        }

                                    // 如果这个星期比上个星期高
                                    if (lastSecondStockWeekAverageKD.getAverageK().doubleValue() <= lastFirstStockWeekAverageKD.getAverageK().doubleValue()) {
                                        goldCross = true;
                                        logger.info("这个星期比上个星期高");
                                    }
                                    // 如果这个星期比上个星期低
                                    if (lastSecondStockWeekAverageKD.getAverageK().doubleValue() >= lastFirstStockWeekAverageKD.getAverageK().doubleValue()) {
                                        deadCross = true;
                                        logger.info("这个星期比上个星期低");
                                    }
                                } else {
                                    logger.warn("没有前两个星期的记录或者不足两个星期，从下一个日期开始处理");

                                    // 更新robot5_account表的total_assets字段
                                    robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                                    continue;
                                }
                            }

                            // 按照条件，过滤股票
                            // 清空robot5_stock_filter表
                            robot5StockFilterDao.truncateTableRobotStockFilter();

                            // close_price金叉死叉ma5
                            if (goldCrossDeadCrossMethod.equals(WeekGoldCrossDeadCrossMethod.CLOSE_PRICE_MA5_GOLD_CROSS_DEAD_CROSS)) {
                                if (goldCross) {
                                    logger.info("操作方向：做多。满足交易条件：close_price金叉ma5出现");

                                    // 向表robot5_stock_filter中插入可以做多的股票的代码
                                    robot5StockFilterDao.insertBullStockCodeFromStockTransactionDataByDate(currentDate);

                                    // 保留所有周线级别收盘价小于布林带中轨的股票
//                                      robot5StockFilterDao.filterWeekClosePriceDownBollMB(currentDate);

                                    // 删除周线级别，上一周close_price死叉ma5的股票
//                                      robot5StockFilterDao.deleteLastWeekClosePriceDeadCrossMa5(currentDate);
                                    // 删除本周周线级别close_price死叉ma5
//                                      robot5StockFilterDao.filterByStockWeekClosePriceMa5GoldCross(currentDate);
                                    // 删除本周close_price比上一周close_price小的股票
                                    robot5StockFilterDao.deleteThisWeekClosePriceLessThanLastWeekClosePrice(currentDate);
                                    // 删除周线级别，KD死叉的股票
//                                      robot5StockFilterDao.filterByStockWeekKDGoldCross(currentDate);
                                    // 删除周线级别，上一周KD死叉的股票
//                                      robot5StockFilterDao.deleteLastWeekKDDeadCross(currentDate);
                                    // 删除上周K比上上周K小的股票
//                                      robot5StockFilterDao.deleteLastWeekKDownThanLastTwoWeekK(currentDate);

                                    // 过滤条件：当前收盘价与某段时间最高价的百分比
//                              robot5StockFilterDao
//                                    .filterByPercentageOfCurrentClosePriceCompareToSomeTimeHighestPrice(
//                                            currentClosePriceCompareToSomeTimeHighestLowestPriceBeginDate, currentDate,
//                                            currentClosePriceCompareToSomeTimeHighestPrice);

                                    // 过滤条件：MA不单调递减，过滤股票
//                            String[] maLevelArray = maNotDecreasingLevel.replace("[", "").replace("]", "").split(",");
//                            String[] dateNumberArray = maNotDecreasingDateNumber.replace("[", "").replace("]", "").split(",");
//                            for (int j = 0; j < maLevelArray.length && j < dateNumberArray.length; j++) {
//                                String maLevel = maLevelArray[j].trim();
//                                String dateNumber = dateNumberArray[j].trim();
//                                robot5StockFilterDao.filterByMANotDecreasing(currentDate, Integer.parseInt(maLevel), dateNumber);
//                            }

                                    // 保留所有金叉的股票
                                    robot5StockFilterDao.filterByAllGoldCross(currentDate);
                                } else if (deadCross) {
                                    logger.info("操作方向：做空。满足交易条件：close_price死叉ma5出现");

                                    // 向表robot5_stock_filter中插入可以做空的股票的代码
                                    robot5StockFilterDao.insertShortStockCodeFromStockTransactionDataByDate(currentDate);

                                    // 保留所有周线级别收盘价大于布林带中轨的股票
//                                      robot5StockFilterDao.filterWeekClosePriceUpBollMB(currentDate);

                                    // 删除周线级别，上一周close_price金叉ma5的股票
//                                      robot5StockFilterDao.deleteLastWeekClosePriceGoldCrossMa5(currentDate);
                                    // 删除本周周线级别close_price金叉ma5
//                                      robot5StockFilterDao.filterByStockWeekClosePriceMa5DeadCross(currentDate);
                                    // 删除本周close_price比上一周close_price大的股票
                                    robot5StockFilterDao.deleteThisWeekClosePriceGreatThanLastWeekClosePrice(currentDate);
                                    // 删除周线级别，KD金叉的股票
//                                      robot5StockFilterDao.filterByStockWeekKDDeadCross(currentDate);
                                    // 删除周线级别，上一周KD金叉的股票
//                                      robot5StockFilterDao.deleteLastWeekKDGoldCross(currentDate);
                                    // 删除上周K比上上周K大的股票1n
//                                      robot5StockFilterDao.deleteLastWeekKUpThanLastTwoWeekK(currentDate);

                                    // 过滤条件：当前收盘价与某段时间最低价的百分比
//                              robot5StockFilterDao
//                                    .filterByPercentageOfCurrentClosePriceCompareToSomeTimeLowestPrice(
//                                            currentClosePriceCompareToSomeTimeHighestLowestPriceBeginDate, currentDate,
//                                            currentClosePriceCompareToSomeTimeLowestPrice);

                                    // 过滤条件：MA不单调递增，过滤股票
//                            String[] maLevelArray = maNotIncreasingLevel.replace("[", "").replace("]", "").split(",");
//                            String[] dateNumberArray = maNotIncreasingDateNumber.replace("[", "").replace("]", "").split(",");
//                            for (int j = 0; j < maLevelArray.length && j < dateNumberArray.length; j++) {
//                                String maLevel = maLevelArray[j].trim();
//                                String dateNumber = dateNumberArray[j].trim();
//                                robot5StockFilterDao.filterByMANotIncreasing(currentDate, Integer.parseInt(maLevel), dateNumber);
//                            }

                                    // 保留所有死叉的股票
                                    robot5StockFilterDao.filterByAllDeadCross(currentDate);
                                } else {
                                    logger.warn("不做处理，因为不满足条件");

                                    // 更新robot4_account表的total_assets字段
                                    robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                                    continue;
                                }
                            }

                            // hei_kin_ashi上涨/下跌
                            if (goldCrossDeadCrossMethod.equals(WeekGoldCrossDeadCrossMethod.HEI_KIN_ASHI_UP_DOWN)) {
                                if (goldCross) {
                                    logger.info("操作方向：做多。满足交易条件：hei_kin_ashi收盘价上涨出现");

                                    // 向表robot5_stock_filter中插入可以做多的股票的代码
                                    robot5StockFilterDao.insertBullStockCodeFromStockTransactionDataByDate(currentDate);

                                    // 保留所有周线级别收盘价小于布林带中轨的股票
//                                      robot5StockFilterDao.filterWeekClosePriceDownBollMB(currentDate);

                                    // 删除周线级别，上一周close_price死叉ma5的股票
//                                      robot5StockFilterDao.deleteLastWeekClosePriceDeadCrossMa5(currentDate);
                                    // 删除周线级别close_price死叉ma5
//                                      robot5StockFilterDao.filterByStockWeekClosePriceMa5GoldCross(currentDate);
                                    // 删除周线级别上一周hei_kin_ashi收盘价小于上上周hei_kin_ashi收盘价的股票
//                                      robot5StockFilterDao.deleteLastWeekHeiKinAshiClosePriceLessThanLastTwoWeekHeiKinAshiClosePrice(currentDate);
                                    // 删除周线级别，上一周hei_kin_ashi收盘价是阴线的股票
//                                      robot5StockFilterDao.deleteLastWeekHeiKinAshiClosePriceNegativeLine(currentDate);
                                    // 删除周线级别，本周hei_kin_ashi收盘价小于上周hei_kin_ashi收盘价的股票
//                                      robot5StockFilterDao.deleteThisWeekHeiKinAshiClosePriceLessThanLastWeekHeiKinAshiClosePrice(currentDate);
                                    // 删除周线级别，本周hei_kin_ashi收盘价是阴线的股票
                                    robot5StockFilterDao.deleteThisWeekHeiKinAshiClosePriceNegativeLine(currentDate);
                                    // 删除周线级别，KD死叉的股票
//                                      robot5StockFilterDao.filterByStockWeekKDGoldCross(currentDate);
                                    // 删除周线级别，上一周KD死叉的股票
//                                      robot5StockFilterDao.deleteLastWeekKDDeadCross(currentDate);
                                    // 删除上周K比上上周K小的股票
//                                      robot5StockFilterDao.deleteLastWeekKDownThanLastTwoWeekK(currentDate);

                                    // 过滤条件：当前收盘价与某段时间最高价的百分比
//                              robot5StockFilterDao
//                                    .filterByPercentageOfCurrentClosePriceCompareToSomeTimeHighestPrice(
//                                            currentClosePriceCompareToSomeTimeHighestLowestPriceBeginDate, currentDate,
//                                            currentClosePriceCompareToSomeTimeHighestPrice);

                                    // 过滤条件：MA不单调递减，过滤股票
//                            String[] maLevelArray = maNotDecreasingLevel.replace("[", "").replace("]", "").split(",");
//                            String[] dateNumberArray = maNotDecreasingDateNumber.replace("[", "").replace("]", "").split(",");
//                            for (int j = 0; j < maLevelArray.length && j < dateNumberArray.length; j++) {
//                                String maLevel = maLevelArray[j].trim();
//                                String dateNumber = dateNumberArray[j].trim();
//                                robot5StockFilterDao.filterByMANotDecreasing(currentDate, Integer.parseInt(maLevel), dateNumber);
//                            }

                                    // 保留所有金叉的股票
                                    robot5StockFilterDao.filterByAllGoldCross(currentDate);
                                } else if (deadCross) {
                                    logger.info("操作方向：做空。满足交易条件：hei_kin_ashi收盘价下跌出现");

                                    // 向表robot5_stock_filter中插入可以做空的股票的代码
                                    robot5StockFilterDao.insertShortStockCodeFromStockTransactionDataByDate(currentDate);

                                    // 保留所有周线级别收盘价大于布林带中轨的股票
//                                      robot5StockFilterDao.filterWeekClosePriceUpBollMB(currentDate);

                                    // 删除周线级别，上一周close_price金叉ma5的股票
//                                      robot5StockFilterDao.deleteLastWeekClosePriceGoldCrossMa5(currentDate);
                                    // 删除周线级别close_price金叉ma5
//                                      robot5StockFilterDao.filterByStockWeekClosePriceMa5DeadCross(currentDate);
                                    // 删除周线级别上一周hei_kin_ashi收盘价大于上上周hei_kin_ashi收盘价的股票
//                                      robot5StockFilterDao.deleteLastWeekHeiKinAshiClosePriceGreatThanLastTwoWeekHeiKinAshiClosePrice(currentDate);
                                    // 删除周线级别，上一周hei_kin_ashi收盘价是阳线的股票
//                                      robot5StockFilterDao.deleteLastWeekHeiKinAshiClosePricePositiveLine(currentDate);
                                    // 删除周线级别，本周hei_kin_ashi收盘价大于上周hei_kin_ashi收盘价的股票
//                                      robot5StockFilterDao.deleteThisWeekHeiKinAshiClosePriceGreatThanLastWeekHeiKinAshiClosePrice(currentDate);
                                    // 删除周线级别，本周hei_kin_ashi收盘价是阳线的股票
                                    robot5StockFilterDao.deleteThisWeekHeiKinAshiClosePricePositiveLine(currentDate);
                                    // 删除周线级别，KD金叉的股票
//                                      robot5StockFilterDao.filterByStockWeekKDDeadCross(currentDate);
                                    // 删除周线级别，上一周KD金叉的股票
//                                      robot5StockFilterDao.deleteLastWeekKDGoldCross(currentDate);
                                    // 删除上周K比上上周K大的股票1n
//                                      robot5StockFilterDao.deleteLastWeekKUpThanLastTwoWeekK(currentDate);

                                    // 过滤条件：当前收盘价与某段时间最低价的百分比
//                              robot5StockFilterDao
//                                      .filterByPercentageOfCurrentClosePriceCompareToSomeTimeLowestPrice(
//                                              currentClosePriceCompareToSomeTimeHighestLowestPriceBeginDate, currentDate,
//                                              currentClosePriceCompareToSomeTimeLowestPrice);

                                    // 过滤条件：MA不单调递增，过滤股票
//                            String[] maLevelArray = maNotIncreasingLevel.replace("[", "").replace("]", "").split(",");
//                            String[] dateNumberArray = maNotIncreasingDateNumber.replace("[", "").replace("]", "").split(",");
//                            for (int j = 0; j < maLevelArray.length && j < dateNumberArray.length; j++) {
//                                String maLevel = maLevelArray[j].trim();
//                                String dateNumber = dateNumberArray[j].trim();
//                                robot5StockFilterDao.filterByMANotIncreasing(currentDate, Integer.parseInt(maLevel), dateNumber);
//                            }

                                    // 保留所有死叉的股票
                                    robot5StockFilterDao.filterByAllDeadCross(currentDate);
                                } else {
                                    logger.warn("不做处理，因为不满足条件");

                                    // 更新robot5_account表的total_assets字段
                                    robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                                    continue;
                                }
                            }

                            // kd金叉/死叉
                            if (goldCrossDeadCrossMethod.equals(WeekGoldCrossDeadCrossMethod.KD_GOLD_CROSS_DEAD_CROSS)) {
                                if (goldCross) {
                                    logger.info("操作方向：做多。满足交易条件：kd金叉出现");

                                    // 向表robot5_stock_filter中插入可以做多的股票的代码
                                    robot5StockFilterDao.insertBullStockCodeFromStockTransactionDataByDate(currentDate);

                                    // 保留所有周线级别收盘价小于布林带中轨的股票
//                                          robot5StockFilterDao.filterWeekClosePriceDownBollMB(currentDate);

                                    // 删除周线级别close_price死叉ma5
//                                          robot5StockFilterDao.filterByStockWeekClosePriceMa5GoldCross(currentDate);
                                    // 删除周线级别，上一周close_price死叉ma5的股票
//                                          robot5StockFilterDao.deleteLastWeekClosePriceDeadCrossMa5(currentDate);
                                    // 删除周线级别KD，上一周死叉的股票
//                                          robot5StockFilterDao.deleteLastWeekKDDeadCross(currentDate);
                                    // 删除周线级别，KD死叉的股票
//                                          robot5StockFilterDao.filterByStockWeekKDGoldCross(currentDate);
                                    // 删除上周K比上上周K小的股票
//                                          robot5StockFilterDao.deleteLastWeekKDownThanLastTwoWeekK(currentDate);
                                    // 删除这周K比上周K小的股票
                                    robot5StockFilterDao.deleteThisWeekKDownThanLastTwoWeekK(currentDate);

                                    // 过滤条件：当前收盘价与某段时间最高价的百分比
//                                  robot5StockFilterDao
//                                    .filterByPercentageOfCurrentClosePriceCompareToSomeTimeHighestPrice(
//                                            currentClosePriceCompareToSomeTimeHighestLowestPriceBeginDate, currentDate,
//                                            currentClosePriceCompareToSomeTimeHighestPrice);

                                    // 过滤条件：MA不单调递减，过滤股票
//                            String[] maLevelArray = maNotDecreasingLevel.replace("[", "").replace("]", "").split(",");
//                            String[] dateNumberArray = maNotDecreasingDateNumber.replace("[", "").replace("]", "").split(",");
//                            for (int j = 0; j < maLevelArray.length && j < dateNumberArray.length; j++) {
//                                String maLevel = maLevelArray[j].trim();
//                                String dateNumber = dateNumberArray[j].trim();
//                                robot5StockFilterDao.filterByMANotDecreasing(currentDate, Integer.parseInt(maLevel), dateNumber);
//                            }

                                    // 保留所有金叉的股票
                                    robot5StockFilterDao.filterByAllGoldCross(currentDate);
                                } else if (deadCross) {
                                    logger.info("操作方向：做空。满足交易条件：kd死叉出现");

                                    // 向表robot5_stock_filter中插入可以做空的股票的代码
                                    robot5StockFilterDao.insertShortStockCodeFromStockTransactionDataByDate(currentDate);

                                    // 保留所有周线级别收盘价大于布林带中轨的股票
//                                          robot5StockFilterDao.filterWeekClosePriceUpBollMB(currentDate);

                                    // 删除周线级别close_price金叉ma5
//                                          robot5StockFilterDao.filterByStockWeekClosePriceMa5DeadCross(currentDate);
                                    // 删除周线级别，上一周close_price金叉ma5的股票
//                                          robot5StockFilterDao.deleteLastWeekClosePriceGoldCrossMa5(currentDate);
                                    // 删除周线级别，上一周KD金叉的股票
//                                          robot5StockFilterDao.deleteLastWeekKDGoldCross(currentDate);
                                    // 删除周线级别，KD金叉的股票
//                                          robot5StockFilterDao.filterByStockWeekKDDeadCross(currentDate);
                                    // 删除上周K比上上周K大的股票
//                                          robot5StockFilterDao.deleteLastWeekKUpThanLastTwoWeekK(currentDate);
                                    // 删除这周K比上周K大的股票
                                    robot5StockFilterDao.deleteThisWeekKUpThanLastTwoWeekK(currentDate);

                                    // 过滤条件：当前收盘价与某段时间最低价的百分比
//                                  robot5StockFilterDao
//                                    .filterByPercentageOfCurrentClosePriceCompareToSomeTimeLowestPrice(
//                                            currentClosePriceCompareToSomeTimeHighestLowestPriceBeginDate, currentDate,
//                                            currentClosePriceCompareToSomeTimeLowestPrice);

                                    // 过滤条件：MA不单调递增，过滤股票
//                            String[] maLevelArray = maNotIncreasingLevel.replace("[", "").replace("]", "").split(",");
//                            String[] dateNumberArray = maNotIncreasingDateNumber.replace("[", "").replace("]", "").split(",");
//                            for (int j = 0; j < maLevelArray.length && j < dateNumberArray.length; j++) {
//                                String maLevel = maLevelArray[j].trim();
//                                String dateNumber = dateNumberArray[j].trim();
//                                robot5StockFilterDao.filterByMANotIncreasing(currentDate, Integer.parseInt(maLevel), dateNumber);
//                            }
                                    // 保留所有死叉的股票
                                    robot5StockFilterDao.filterByAllDeadCross(currentDate);
                                } else {
                                    logger.warn("不做处理，因为不满足条件");

                                    // 更新robot5_account表的total_assets字段
                                    robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                                    continue;
                                }
                            }

                            // 过滤条件：只保留这个价格区间以内的股票
                            robot5StockFilterDao.filterByLessThanClosePrice(currentDate, closePriceStart, closePriceEnd);
                            // 过滤条件：删除除过权的股票
//                            robot5StockFilterDao.filterByXr(currentDate, endDate);
                            robot5StockFilterDao.filterByXr(beginDate, endDate);

                            // 如果当前日期是周末，则买股票，否则跳过这一天
                            if (isWeekend) {
                                // 买股票/卖股票
                                robot5StockTransactRecordDao.buyOrSell(currentDate, 4, useWeekHoldStockNumber, holdStockNumber);

                                // 更新robot5_account表的total_assets字段
                                robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);
                            }
                        }
                    } else {
                        logger.warn("没有前两个星期的记录或者不足两个星期，从下一个日期开始处理");

                        // 更新robot5_account表的total_assets字段
                        robot5AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                        continue;
                    }
                }

                // 获取买卖建议
                String printText = null;
                if (printFormat.equals(RobotPrintBuySellSuggestionFormat.JSON)) {
                    // json方式
                    printText = super.printBuySellSuggestionByJson_multipleMethod(currentDate);
                }
                if (printFormat.equals(RobotPrintBuySellSuggestionFormat.SIMPLE)) {
                    // 简单文本格式
                    printText = super.printBuySellSuggestionBySimple_multipleMethod(currentDate);
                }
                logger.info("买卖建议：\n" + printText);
            }
        }

        logger.info("执行某段时间内的股票买卖交易完成（多种方法一起使用）");
    }

    @Override
    public String listToString(List list) {
        return null;
    }
}
